package edu.xlh.travel.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import edu.xlh.travel.common.Result;
import edu.xlh.travel.dao.NoticeDao;
import edu.xlh.travel.pojo.*;
import edu.xlh.travel.service.NoticeService;
import edu.xlh.travel.util.AnnouncementDataFormatParsing;
import edu.xlh.travel.util.DateTimeUtil;
import edu.xlh.travel.util.IdWorker;
import edu.xlh.travel.util.PageResult;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpSession;
import java.util.*;

@Service
@Transactional
public class NoticeServiceImpl implements NoticeService {
    @Autowired
    private NoticeDao noticeDao;
    @Autowired
    private IdWorker idWorker;
    @Override
    public Result getlasterNotice(HttpSession session) {
        User user = (User)session.getAttribute("admin");
        if (user == null) {
            return new Result(201);
        }
        List<Notice> noticeList = noticeDao.findTOP6ByOrderByIssuedTimeDesc();
        List<Notice> noticeListIsNotNull = new ArrayList<>();
        noticeList.stream().forEach(item -> {
            if ("0".equals(item.getDelFlag())) {
                noticeListIsNotNull.add(item);
            }
        });
        return new Result(200 , "最新公告数据获取成功" , noticeListIsNotNull);
    }

    @Override
    public Result issuedNotice(HashMap hashMap, HttpSession session) {
        User user = (User)session.getAttribute("admin");
        if (user == null) {
            return new Result(201);
        }
        String htmlData = (String) hashMap.get("htmlData");
        String jsonData = (String) hashMap.get("jsonData");
        String title = (String) hashMap.get("title");
        List list = JSON.parseObject(jsonData, List.class);
        //获取标题头
        //String title = AnnouncementDataFormatParsing.fnParseData(list);
        //截取html格式中开头标题部分
        int end = htmlData.lastIndexOf("\"");
        String virContent = htmlData.substring(1, end );
        int firstHTag = virContent.indexOf("<h");
        String reallyContent ="暂时没有内容";
        if(firstHTag == 0) {
            int firstHEndTag = virContent.indexOf("</h");
            reallyContent  = virContent.substring(firstHEndTag + 5);
        }

        Notice notice = new Notice();
        notice.setId(idWorker.nextId() + "")
                .setTitle(title)
                .setContent(virContent)
                .setIssuedTime(new Date())
                .setDelFlag("0");
        Notice save = noticeDao.save(notice);
        if (save != null) {
            return new Result(200 , "公告发布成功");
        }
        return new Result(201 , "公告发布失败");
    }

    @Override
    public Result findAllNotice(int page, int limit , HttpSession session) {
        User user = (User)session.getAttribute("admin");
        if (user == null) {
            return new Result(201);
        }
        Specification specification = new Specification() {
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> noticeList = new ArrayList<>();
                noticeList.add(criteriaBuilder.equal(root.get("delFlag"), "0"));
                return criteriaBuilder.and(noticeList.toArray(new Predicate[noticeList.size()]));
            }
        };
        Sort sort = Sort.by(Sort.Direction.DESC, "issuedTime");
        Pageable pageable= PageRequest.of(page-1,limit ,sort);
        Page<Notice> noticePage = noticeDao.findAll(specification, pageable);
        if (noticePage!=null) {
            return new Result(0 , "公告分页数据获取成功" , new PageResult<Notice>(noticePage.getTotalElements(), noticePage.getContent()));
        }
        return new Result(200 , "公告列表数据返回成功失败");
    }

    @Override
    public Result edit(String id , Notice notice, HttpSession session) {
        User user = (User)session.getAttribute("admin");
        if (user == null) {
            return new Result(201,"会话过期，请重新登陆");
        }
        notice.setId(id);
        notice.setIssuedTime(new Date());
        try {
            noticeDao.updateNoticeByNoticeId(notice);
        } catch (Exception e) {
            return new Result(201 , "公告数据修改失败");
        }
        return new Result(200 , "公告数据修改成功");
    }

    @Override
    public Result deleteById(String id, HashMap hashMap, HttpSession session) {
        User user = (User)session.getAttribute("admin");
        if (user == null) {
            return new Result(201,"会话过期，请重新登陆");
        }
        String noticeId = (String) hashMap.get("id");
        if (id.equals(noticeId)) {
            try {
                noticeDao.updateNoticeDelFlagByNoticeId(noticeId , "1");
            } catch (Exception e) {
                return new Result(201 , "id为"+noticeId+"的公告记录"+"删除失败");
            }
        } else {
            return new Result(202 , "id为"+noticeId+"的公告id有问题");
        }
        return new Result(200 , "id为"+noticeId+"的公告记录"+"删除成功");
    }

    @Override
    public Result batchDelete(JSONArray jsonArray, HttpSession session) {
        List<Notice> noticeList = JSON.parseArray(jsonArray.toJSONString() , Notice.class);
        try {
            noticeList.stream().iterator().forEachRemaining(notice -> {
                noticeDao.updateNoticeDelFlagByNoticeId(notice.getId() , "1");
            });
        }catch (Exception e) {
            return new Result(201);
        }
        return new Result(200);
    }

    @Override
    public Result QueryNoticeByCondition(Integer page, Integer limit , Notice notice, HttpSession session) {
        User userFromSession = (User)session.getAttribute("admin");
        if (userFromSession == null) {
            return new Result(201,"会话过期，请重新登陆");
        }

        Specification specification = new Specification() {
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> noticeList = new ArrayList<>();
                if (StringUtils.isNotEmpty(notice.getTitle())) {
                    noticeList.add(criteriaBuilder.like(root.get("title") , notice.getTitle()));
                }
                if (notice.getIssuedTime() != null) {
                    String issuedTime = DateTimeUtil.dateToStr(notice.getIssuedTime(), "yyyy-MM-dd");
                    String issuedTimeStartTimeToStr = issuedTime + " " + "00:00:00";
                    String issuedTimeEndTimeToStr = issuedTime + " " + "23:59:59";
                    Date issuedTimeStartTimeToDate = DateTimeUtil.strToDate(issuedTimeStartTimeToStr , "yyyy-MM-dd HH:mm:ss");
                    Date issuedTimeEndTimeToDate = DateTimeUtil.strToDate(issuedTimeEndTimeToStr , "yyyy-MM-dd HH:mm:ss");
                    noticeList.add(criteriaBuilder.between(root.get("issuedTime") ,  issuedTimeStartTimeToDate , issuedTimeEndTimeToDate));
                }

                noticeList.add(criteriaBuilder.equal(root.get("delFlag") ,"0"));
                return criteriaBuilder.and(noticeList.toArray(new Predicate[noticeList.size()]));
            }
        };
        Pageable pageable= PageRequest.of(page-1,limit);
        Page<Notice> noticeListPage  = noticeDao.findAll(specification , pageable);
        if (noticeListPage!=null) {
            return new Result(0 , "公告列表分页数据获取成功" , new PageResult<Notice>(noticeListPage.getTotalElements(), noticeListPage.getContent()));
        }
        return new Result(201 , "公告列表列表失败");
    }

    @Override
    public Result findById(String id, HttpSession session) {
        User userFromSession = (User)session.getAttribute("admin");
        if (userFromSession == null) {
            return new Result(201,"会话过期，请重新登陆");
        }
        try{
            Notice notice = noticeDao.findById(id).get();
            return new Result(200 , "数据回显成功" , notice);
        } catch (Exception e) {
            return new Result(202 , "数据回显失败");
        }
    }

    @Override
    public Result editNotice(String noticeId, Notice notice, HttpSession session) {
        User userFromSession = (User)session.getAttribute("admin");
        if (userFromSession == null) {
            return new Result(201,"会话过期，请重新登陆");
        }
        String content = notice.getContent();
        int end = content.lastIndexOf("\"");
        notice.setId(noticeId)
                .setContent(content.substring(1, end ))
                .setIssuedTime(new Date());

        try {
            noticeDao.updateNoticeByNoticeId(notice);
            return new Result(200 , "公告修改成功");
        } catch (Exception e) {
            return new Result(202 , "公告修改失败");
        }
    }
}
